package cn.gqr.service.Impl;

import cn.gqr.entity.Book;
import cn.gqr.entity.Largefile;
import cn.gqr.entity.NewBook;
import cn.gqr.mapper.BookMapper;
import cn.gqr.service.BookService;

import cn.gqr.service.HotService;
import cn.gqr.tool.RespJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    BookMapper bookMapper;
    @Autowired
    HotService hotService;

    //全查询
    @Override
    public List<NewBook> findAll() {
        return bookMapper.findAll();
    }

    //id查询
    @Override
    public NewBook findById(int id) {
        return bookMapper.findById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> bookAddOrUpd(NewBook book, MultipartFile file, Largefile largefile){
        if(book.getId()==0){
            if(file==null){
                return RespJson.pack(200,"图片未上传",null);
            }
            //上传图片，返回图片的uuid
            String uuid = hotService.filesUpload(largefile, file);
            //设置book的图片uuid
            book.setPicture(uuid);
            int i = bookMapper.addBook(book);
            return RespJson.pack(200,i==0?"添加失败":"添加成功",i==0?null:uuid);
        }
        if(book.getId()>0){
            if(file != null){
                //根据id查询
                NewBook bok = findById(book.getId());
                //根据uuid删除图片
                hotService.delPic(bok.getPicture());
                //添加图片,并返回添加的图片的uuid
                String uuid = hotService.filesUpload(largefile, file);
                //给book赋值uuid
                book.setPicture(uuid);
            }
            int update = bookMapper.update(book);
            return RespJson.pack(200,update==0?"修改失败":"修改成功",update);
        }

        return RespJson.pack(200,"添加修改失败",null);
    }


    //分页查询
    @Override
    public List<NewBook> findByPage(int start, int num) {
        return bookMapper.findByPage(start,num);
    }
    //查询总行数
    @Override
    public int findByLine() {
        return bookMapper.findByLine();
    }
}
